package com.ja.controller.v1;

import com.alibaba.fastjson.JSON;
import com.ja.config.WebsiteStateConfig;
import com.ja.domain.*;
import com.ja.sevice.*;
import com.ja.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 项目名称：cp
 * 类名称：V1GlobalController.java
 * 类描述：
 * 创建人：   Administrator
 * 创建时间：2019年3月1日 下午5:39:52
 * @version v1.0.0
 */
@RequestMapping("/v1")
@Controller
public class V1GlobalController {

	@Autowired
	private IUserService userService;

	@Autowired
	private ISystemConfigService systemConfigService;

	@Autowired
	private IAdminService adminService;

	@Autowired
	private ILotteryService lotterService;

	@Autowired
	private IOrderService orderService;

	@Autowired
	private IJointService jointService;

	@Autowired
	private JineService jineService;

	@Autowired
	private DamaService damaService;

	@Autowired
	private IDataService dataService;

	@Autowired
	private ILotteryService lotteryService;

	@Autowired
	private LiushuiService liushuiService;

	@Autowired
	private GendanService gendanService;

	@Autowired
	private QqKeFuService qqKeFuService;

	@Autowired
	private InfoNoticeService infoNotiService;

	@Autowired
	private GendanlvService gendanlvService;

	@Autowired
	private FanshuiJlService fanshuiJlService;

	@Autowired
	private AgencyCenterSevice agencyCenterSevice;

	/**
	 *
	 * ----TODO：系统配置信息
	 *
	 */

	/**
	 * 方法名：findWebsiteConfigInfo
	 * 描述：    查询网站的基本配置信息
	 * 参数：    @return
	 * @return: json
	 */
	@ResponseBody
	@RequestMapping(value = "/title", produces = {"application/json;charset=UTF-8"})
	public String findWebsiteConfigInfo(){
		Map<String,Object> map =new HashMap<>();
		Admin admin = new Admin();
		admin.setNotice(WebsiteStateConfig.configs.get("notice"));
		admin.setWangzhantitle(WebsiteStateConfig.configs.get("wangzhantitle"));
		admin.setKefusbtime(WebsiteStateConfig.configs.get("kefusbtime"));
		admin.setKefuxbtime(WebsiteStateConfig.configs.get("kefuxbtime"));
		admin.setFanshuiContent(WebsiteStateConfig.configs.get("fanshuiContent"));
		admin.setFanshuiPicture(WebsiteStateConfig.configs.get("fanshuiPicture"));
		admin.setPc_notice(WebsiteStateConfig.configs.get("pc_notice"));
		admin.setLogo(WebsiteStateConfig.configs.get("logo"));
		admin.setPc_welcome(WebsiteStateConfig.configs.get("pc_welcome"));
		admin.setPc_wechat(WebsiteStateConfig.configs.get("pc_wechat"));
		admin.setBuy1(Integer.parseInt(WebsiteStateConfig.configs.get("buy1")));
		admin.setBuy2(Integer.parseInt(WebsiteStateConfig.configs.get("buy2")));
		admin.setBuy3(Integer.parseInt(WebsiteStateConfig.configs.get("buy3")));
		admin.setBuy4(Integer.parseInt(WebsiteStateConfig.configs.get("buy4")));
		admin.setBuy5(Integer.parseInt(WebsiteStateConfig.configs.get("buy5")));
		map.put(DateUtil.getCurrTime(),admin);
			return JSON.toJSONString(map);
	}

	/**
	 *
	 * ----TODO：主页管理
	 *
	 */

	/**
	 * 方法名：mobileIndex
	 * 描述：    手机端首页页面
	 * 参数：    @param request
	 * 参数：    @param session
	 * 参数：    @return
	 * @return: ModelAndView
	 */
	@RequestMapping("/sy")
	public ModelAndView mobileIndex(HttpServletRequest request,HttpSession session) {
		ModelAndView model = new ModelAndView("include/sy");
		String ip = IpAddrUtil.getIpAddr(request);
		userService.addTourists(ip, "首页");
		if (request.getQueryString() != null) {
			String refCode = request.getServerName() + "?" + (request.getQueryString());
			session.setAttribute("refCode", refCode);
		}
		return model;
	}

	 /**
	  *   方法名：updatePage
	  *   描述：    更新用户缓存页面
	  *   参数：    @return
	  * @return: JsonResult
	  */
	 @ResponseBody
	 @RequestMapping("/updatePage")
	 public JsonResult updatePage() {
		 return new JsonResult(WebsiteStateConfig.configs.get("weihukaiguan"),infoNotiService.updatePage());
	 }

	 /**
	  * 方法名：homePageData
	  * 描述：     查询首页需要使用的数据
	  * 参数：    @param session
	  * 参数：    @return
	  * @return: JsonResult  查询到则返回list集合包含colorVariety实体数据 没有查询到则返回空集合
	  */
	 @ResponseBody
	 @RequestMapping("/homePageData")
	 public JsonResult homePageData(HttpSession session) {
		 List<ColorVariety> list = new ArrayList<ColorVariety>();//彩种的状态  1开启  2关闭
		 for(Lotter l : WebsiteStateConfig.lotteryState) {
			 if(!"jlk3".equals(l.getCname().trim()) && !"klpk".equals(l.getCname().trim())  && !"zc".equals(l.getCname().trim())  && !"jnd28".equals(l.getCname().trim())) {
				 list.add(new ColorVariety(l.getCname(),l.getState()));
			 }
		}
		List<QqKeFu> list1 = qqKeFuService.getAllQqKeFu();//获取客服信息
		Notice n = new Notice();//首页公告
		IndexPicture ipe = infoNotiService.getOneByPictureDesc();
		InfoNotice ifne =  infoNotiService.getOneByNoticeDesc("首页公告");
		n.setWangzhantitle(WebsiteStateConfig.configs.get("wangzhantitle"));
		n.setNotice(WebsiteStateConfig.configs.get("notice"));
		n.setPicturePath1(ipe.getPicturePath1());
		n.setPicturePath2(ipe.getPicturePath2());
		n.setPicturePath3(ipe.getPicturePath3());
		n.setPicturePath4(ipe.getPicturePath4());
		n.setPicturePath5(ipe.getPicturePath5());
		n.setNoticePicture(ifne.getNoticePicture());
		n.setNoticeName(ifne.getNoticeName());
		n.setKefusbtime(WebsiteStateConfig.configs.get("kefusbtime"));
		n.setKefuxbtime(WebsiteStateConfig.configs.get("kefuxbtime"));

		DecimalFormat df = new DecimalFormat("0.00");
		String[] str = {  "北京PK拾","二分PK拾", "幸运赛马","幸运飞艇", "重庆时时彩", "二分时时彩", "天津时时彩","新疆时时彩", "广东快乐十分", "重庆快乐十分", "安徽11选5",
				"广东11选5", "江西11选5", "山东11选5", "上海11选5", "排列三", "福彩3D", "安徽快3", "广西快3", "江苏快3", "北京快3","三分快3","香港六合彩","五分六合彩",
				"北京28","幸运28","加拿大28","百家乐" };//中奖数据
		List<Sy> list2 = new ArrayList<Sy>();
		for (int i = 0; i < str.length-1; i++) {
			Sy o1 = new Sy();
			o1.setHuiyuanzh(createUserName(4));
			o1.setCname1(str[createLotteryName(str.length - 1)]);
			o1.setGoalmoney(new Double(df.format((Math.random() * 1000))));
			list2.add(o1);
		}
		User user = (User)session.getAttribute("user");
		if(user == null) {//判断用户是否在登录状态
			return new JsonResult(null,0,list,list1,list2,n);
		}
		if(user.getState()==1 || user.getState()==3) {
			return new JsonResult(user.getAvatar(),1,list,list1,list2,n);
		}else if(user.getState()==2) {
			return new JsonResult(user.getAvatar(),2,list,list1,list2,n);
		}
		return new JsonResult("error","error");
	 }

	 /**
	  *
	  * ----TODO：注册管理
	  *
	  */

	 /**
	  *   方法名：code
	  *   描述：     生成验证码
	  *   参数：    @param request
	  *   参数：    @param response
	  *   参数：    @throws Exception
	  * @return: int
	  */
	 @RequestMapping("/code")
	 public int code(HttpServletRequest request, HttpServletResponse response) throws Exception {
		 CodeUtil.createdCode(request, response);
		 return 1;
	 }

	/**
	 *  用户注册
	 * @param request 当前请求对象
	 * @param session session对象
	 * @param name 用户名称
	 * @param pass 用户密码
	 * @param icode 邀请码
	 * @param qq 用户QQ
	 * @param code 验证码
	 * @param telephone 电话号码
	 * @return
	 */

	@RequestMapping("/register")
	@ResponseBody
	public synchronized JsonResult register(HttpServletRequest request, HttpSession session, String name, String pass, String icode,
			String qq, String code, String telephone) {
		synchronized (this) {
			if(name.length()>10||name.length()<4) {
				return new JsonResult("5","用户名的长度必须4-10位");
			}
			if(UserNameUtil.isSpecialChar(name)) {
				return new JsonResult("5", "用户名不能包含特殊字符");
			}
			if(UserNameUtil.isContainChinese(name)) {
				return new JsonResult("5", "用户名不能包含中文字符");
			}
				User iuser = userService.checkUser(name);
				if(iuser!=null) {
					return new JsonResult("4", "用户名已存在");
				}
			try {
				String codee = (String) session.getAttribute("code");
				if (!codee.toUpperCase().equals(code.toUpperCase())) {
					return new JsonResult("2", "验证码错误!");
				}
			} catch (Exception e) {
				new JsonResult("0","请刷新验证码!");
			}

			//注册ip地址
			String ip = IpAddrUtil.getIpAddr(request);
			if (!systemConfigService.ipCheck(ip,1)) {
				return new JsonResult("3", "注册次数过多，请明日注册!");
			}
			//用户注册
			int num = userService.register(session,request,name, pass, icode, qq, ip, telephone);
			String md5 = DigestUtils.md5DigestAsHex(pass.getBytes());
			String pwd = DigestUtils.md5DigestAsHex(md5.getBytes());
			User user = userService.login(name, pwd);
			session.setAttribute("user", user);
			WebSocketJson w = new WebSocketJson(4,user.getName());
			w.sendAllHt();
			Set<User> set = SessionListenerUtil.onlineNum(request);
			if(set.size() > 0) {
				WebSocketJson w1 = new WebSocketJson(2,set.size());
				w1.sendHt();
			}
			return new JsonResult(String.valueOf(num), "恭喜你,注册成功");
		}
	}

	 /**
	  *
	  * ----TODO：登录管理
	  *
	  */

	/**
	 * 用户登录
	 * @param request 当前请求对象
	 * @param session 当前session对象
	 * @param name 用户帐号
	 * @param pass 用户密码
	 * @param code 验证码
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public JsonResult login(HttpServletRequest request, HttpSession session, String name, String pass, String code) {
		String ip1 = IpAddrUtil.getIpAddr(request);
		if(session.getAttribute("user")!=null) {
			return new JsonResult("4", "登录成功");
		}
		userService.addTourists(ip1, "登录");
		try {
			String scode = (String) session.getAttribute("code");
			if (!scode.toUpperCase().equals(code.toUpperCase())) {
				//1 验证码输入错误 请从新输入
				return new JsonResult("1", "验证码输入错误!");
			}
		} catch (Exception e) {
			//0 请刷新验证码
			return new JsonResult("0","请刷新验证码");
		}
		User user = userService.login(name, DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(pass.getBytes()).getBytes()));
		if(user!=null) {
			if (user.getState() == 0) {
				//2 账号已被管理员禁用，请联系客服
				return new JsonResult("2", "账号已被禁用，请联系管理员");
			} else if (user.getState() == 1) {
				// 最后登录ip
				String ip = IpAddrUtil.getIpAddr(request);
				WhiteList whiteList = systemConfigService.findWhiteListByIP(ip);
				if (whiteList != null && whiteList.getStatus() == 0) {
					//改ip已经被禁用，请更换ip重新登录
					return new JsonResult("3", "该ip被禁用，请更换ip重新登录");
				}
				// 未登录时间
				String retime = user.getLastTime();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				long t1 = 0;
				String t3 ="";
				try {
					t1 = sdf.parse(retime).getTime();
					t3 = "未登录"+(int) (((new Date().getTime() - t1) / 1000) / 86400) + "天";
				} catch (ParseException e) {
				}
				user.setLastTime(DateUtil.getCurrTime());
				user.setNotTime(t3);
				user.setLastIp(ip);
				userService.updateUserInfo(user);
				new WebSocketJson(7,name,"你的账号在另外一个地方登陆，如果不是你本人操作请及时修改密码").send();
				SessionListenerUtil.singleLogin(request, name);
				session.setAttribute("user", user);
				//添加页面更新，请勿删除
				/*UpdataTable updataTable =  infoNotiService.updatePage();
				UpdataTable updataTable1 =  new UpdataTable();
				updataTable1.setSy(String.valueOf(new Integer(updataTable.getSy())+1));
				aService.updateSystem(updataTable1);*/
				WebSocketJson w = new WebSocketJson(3,user.getName());
				w.sendAllHt();
				Set<User> set = SessionListenerUtil.onlineNum(request);
				if(set.size() > 0) {
					WebSocketJson w1 = new WebSocketJson(2,set.size());
					w1.sendAllHt();
				}
				return new JsonResult("4", "登录成功");
			} else {
				SessionListenerUtil.singleLogin(request, name);
				session.setAttribute("user", user);
				WebSocketJson w = new WebSocketJson(3,user.getName());
				w.sendAllHt();
				Set<User> set = SessionListenerUtil.onlineNum(request);
				if(set.size() > 0) {
					WebSocketJson w1 = new WebSocketJson(2,set.size());
					w1.sendAllHt();
				}
				return new JsonResult("4", "登录成功");
			}
		}else {
			return new JsonResult("5", "账号或者密码错误");//5账号密码错误
		}
	}

	/**
	 *
	 *----TODO：试玩登录
	 *
	 */

	/**
	 * 方法名：tryPlayAcount
	 * 描述：     生成试玩账号
	 * 参数：    @return
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/tryPlayAcount")
	public JsonResult tryPlayAcount() {
		String str = "guest";
		Random random = new Random();
		while (true) {
			String acount = str + random.nextInt();
			User user = userService.checkUser(acount);
			if(user==null) {
				return new JsonResult("success",acount);
			}
		}
	}

	/**
	 * 方法名：tryplay
	 * 描述：    试玩帐号注册
	 * 参数：    @param users
	 * 参数：    @param name 用户名
	 * 参数：    @param pass 用户密码
	 * 参数：    @param session
	 * 参数：    @param request
	 * 参数：    @return
	 * @return: JsonResult
	 */
	@RequestMapping("/tryplay")
	@ResponseBody
	public JsonResult tryplay(User user,HttpSession session,HttpServletRequest request) {
		User users = (User)session.getAttribute("user");
		if(users != null) {
			return new JsonResult("10","你已经登录不可在试玩！");
		}
		if(UserNameUtil.isSpecialChar(user.getName())) {
			return new JsonResult("5", "用户名不能包含特殊字符!");
		}
		if(user.getName().length()>25||user.getName().length()<4) {
			return new JsonResult("5","用户名的长度必须4-10位!");
		}
		if(UserNameUtil.isContainChinese(user.getName())) {
			return new JsonResult("5", "用户名不能包含中文字符!");
		}
		String ipAddress = IpAddrUtil.getIpAddr(request);
		if (!systemConfigService.ipCheck(ipAddress,2)) {
			return new JsonResult("2", "试玩次数过多，请明日注册！");
		}
		synchronized (this) {
			userService.addTourists(ipAddress, "试玩账号");
			User iuser = userService.checkUser(user.getName());
			String pass = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(user.getPass().getBytes()).getBytes());
			if(iuser!=null) {
				if(!pass.equals(iuser.getPass())) {
					return new JsonResult("3", "密码错误,请重新登录或注册试玩账号！");
				}else {
					session.setAttribute("user", iuser);
					return new JsonResult("1", "success");
				}
			}
			user.setPass(pass);
			user.setRegisterIp(ipAddress);
			user.setLastIp(ipAddress);
			userService.userTryplay(user);
			User userInfo = userService.login(user.getName(), pass);
			session.setAttribute("user", userInfo);
			return new JsonResult("1", "success");
		}
	}







	@RequestMapping("/f")
	public void f() {
	}

	@RequestMapping("/fanshuijsp")
	public String fanshui() {
		return "/u/fanshui";
	}

	/**
     *   方法名：findOnelotter
     *   描述：      查询单个彩种的信息
     *   参数：     cname 彩种名称
     *   参数：    @return
	 * @return: JsonResult
	 */
	@RequestMapping("/findOnelotter")
	@ResponseBody
	public JsonResult findOnelotter(String cname) {
		return new JsonResult("",lotterService.findOnelotter(cname));
	}

	/**
     *   方法名：findOneData
     *   描述：     查询单条的开奖信息
	 *   参数：    @param cname 彩种名称
	 *   参数：    @param period 当前期号
	 *   参数：    @return
	 * @return: JsonResult
	 */
	@RequestMapping("/findOneData")
	@ResponseBody
	public JsonResult findOnelotter(String cname,String period) {
		return new JsonResult("",dataService.getLotteryDate(period,cname));
	}

	/**
	 *
	 *   方法名：lotterDatas
	 *   描述：     根据时间查询彩种的开奖信息
	 *   参数：    @param cname 彩种名称
	 *   参数：    @param type 查询类型
	 *   参数：    @return
	 * @return: JsonResult
	 */
	@RequestMapping("/lotterDatas")
	@ResponseBody
	public JsonResult lotterDatas(String cname,Integer type) {
		return new JsonResult("",dataService.lotterDatas(cname,type));
	}


	/** 跟单排行 */
	@RequestMapping("/lotteryrecord")
	public ModelAndView lotteryrecord() {
		ModelAndView m = new ModelAndView("/include/lotteryrecord");
		List<LotterExample> lotterList = lotterService.getAllLotters();
		m.addObject("list", lotterList);
		return m;
	}

	/**
	 * 方法名：syLotterr
	 * 描述：     查询所有正常开奖的彩种
	 * 参数：    @return
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping(value = "/syLotterr", produces = {"application/json;charset=UTF-8"})
	public String syLotterr() {
		Map<String,Object> map =new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		List<LotterExample> lotterList = lotterService.getAllLotters();
		List<LotterExample> list = new ArrayList<LotterExample>();
		List<LotterExample> lotter = new ArrayList<LotterExample>();
		for(LotterExample data :lotterList) {
			if("kuai3".equals(data.getClasst().split(" ")[2])) {
				data.setNextStopOrderTimeEpoch(data.getNextStopOrderTimeEpoch().replaceAll("-", "/"));//如果是快3放到新集合
				list.add(data);
			}else {
				data.setNextStopOrderTimeEpoch(data.getNextStopOrderTimeEpoch().replaceAll("-", "/"));
				lotter.add(data);
			}
		}
		list.addAll(lotter);
		map.put(sdf.format(new Date()),list);
		return JSON.toJSONString(map);
		//return new JsonResult(sdf.format(new Date()),list);
	}
	/**
	 * 根据彩种名查询当前彩种的赔率已经开奖信息
	 * @param cname  彩种名称
	 * @return  返回当前彩种的 赔率以及开奖数据
	 */
	@ResponseBody
	@RequestMapping(value = "/syLotterrs",produces = {"application/json;charset=UTF-8"})
	public String syLotterrs(HttpServletRequest request,String cname) {
		Map<String,Object> map =new HashMap<>();
		String header = request.getHeader("Token");
		System.out.println(header);
		Double odds = 0.00;//计算出他上级给他调的赔率
		if(header!=null){
			try {
				String idStr = new String(DataEncryptUtil.decryptBASE64(header));
				int id = Integer.parseInt(idStr);
				User user = userService.getUserByid(id);

				if(user.getOdds() != null) {
					odds += user.getOdds();
				}
				if(user.getOdds() != null && user.getOdds() > 0) {
					List<User> list = agencyCenterSevice.treeDataobject(user.getFid());
					for (User u : list) {
						if(u.getOdds() != null) {
							odds+=u.getOdds();
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}


		//获取赔率
		LotterExample lotters = lotterService.syLotterrs(cname);//根据传入的彩种名称 查询彩种的赔率以及开奖数据
		if(lotters.getNextStopOrderTimeEpoch() != null) {
			lotters.setNextStopOrderTimeEpoch(lotters.getNextStopOrderTimeEpoch().replaceAll("-", "/"));
		}
		lotters.setRebate1(oddsTransformation(lotters.getRebate1().toString().split(","),odds));
		lotters.setRebate2(oddsTransformation(lotters.getRebate2().toString().split(","),odds));
		lotters.setRebate3(oddsTransformation(lotters.getRebate3().toString().split(","),odds));
		lotters.setRebate4(oddsTransformation(lotters.getRebate4().toString().split(","), odds));
		lotters.setRebate5(oddsTransformation(lotters.getRebate5().toString().split(","), odds));
		lotters.setRebate6(oddsTransformation(lotters.getRebate6().toString().split(","), odds));
		lotters.setRebate7(oddsTransformation(lotters.getRebate7().toString().split(","), odds));
		lotters.setRebate8(oddsTransformation(lotters.getRebate8().toString().split(","), odds));
		lotters.setRebate9(oddsTransformation(lotters.getRebate9().toString().split(","), odds));
		lotters.setRebate10(oddsTransformation(lotters.getRebate10().toString().split(","), odds));
		lotters.setRebate11(oddsTransformation(lotters.getRebate11().toString().split(","), odds));
		lotters.setRebate12(oddsTransformation(lotters.getRebate12().toString().split(","), odds));
		lotters.setRebate13(oddsTransformation(lotters.getRebate13().toString().split(","), odds));
		lotters.setRebate14(oddsTransformation(lotters.getRebate14().toString().split(","), odds));
		lotters.setRebate15(oddsTransformation(lotters.getRebate15().toString().split(","), odds));
		lotters.setRebate16(oddsTransformation(lotters.getRebate16().toString().split(","), odds));
		lotters.setRebate17(oddsTransformation(lotters.getRebate17().toString().split(","), odds));
		lotters.setRebate18(oddsTransformation(lotters.getRebate18().toString().split(","), odds));
		lotters.setRebate19(oddsTransformation(lotters.getRebate19().toString().split(","), odds));
		lotters.setRebate20(oddsTransformation(lotters.getRebate20().toString().split(","), odds));
		lotters.setRebate21(oddsTransformation(lotters.getRebate21().toString().split(","), odds));
		lotters.setRebate22(oddsTransformation(lotters.getRebate22().toString().split(","), odds));
		lotters.setRebate23(oddsTransformation(lotters.getRebate23().toString().split(","), odds));
		lotters.setRebate24(oddsTransformation(lotters.getRebate24().toString().split(","), odds));
		lotters.setRebate25(oddsTransformation(lotters.getRebate25().toString().split(","), odds));
		lotters.setRebate26(oddsTransformation(lotters.getRebate26().toString().split(","), odds));
		lotters.setRebate27(oddsTransformation(lotters.getRebate27().toString().split(","), odds));
		lotters.setRebate28(oddsTransformation(lotters.getRebate28().toString().split(","), odds));
		lotters.setRebate29(oddsTransformation(lotters.getRebate29().toString().split(","), odds));
		lotters.setRebate30(oddsTransformation(lotters.getRebate30().toString().split(","), odds));
		lotters.setRebate31(oddsTransformation(lotters.getRebate31().toString().split(","), odds));
		lotters.setRebate32(oddsTransformation(lotters.getRebate32().toString().split(","), odds));
		lotters.setRebate33(oddsTransformation(lotters.getRebate33().toString().split(","), odds));
		lotters.setRebate34(oddsTransformation(lotters.getRebate34().toString().split(","), odds));
		lotters.setRebate35(oddsTransformation(lotters.getRebate35().toString().split(","), odds));
		lotters.setRebate36(oddsTransformation(lotters.getRebate36().toString().split(","), odds));
		lotters.setRebate37(oddsTransformation(lotters.getRebate37().toString().split(","), odds));
		lotters.setRebate38(oddsTransformation(lotters.getRebate38().toString().split(","), odds));
		lotters.setRebate39(oddsTransformation(lotters.getRebate39().toString().split(","), odds));
		lotters.setRebate40(oddsTransformation(lotters.getRebate40().toString().split(","), odds));
		//return new JsonResult(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()),lotters);
		map.put("data",lotters);
		Lotter timespace = lotterService.getByCname(cname);
		map.put("timespace",timespace.getTimespace());
		map.put("systemTime",new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));


		return JSON.toJSONString(map);
	}
	/**
	 * 计算得出用户的最终赔率并返回结果
	 * @param str 赔率数组
	 * @param odds 上级调动的赔率
	 * @return 返回用户的最终赔率
	 */
	public String oddsTransformation(String str[],Double odds) {
		StringBuffer sbr = new StringBuffer();
		for(int i = 0;i<str.length;i++) {
			sbr.append(odds(str[i],odds)+",");
		}
		return sbr.toString();
	}
	/**
	 * 计算用户的最终赔率
	 * @param str
	 * @param odds
	 * @return
	 */
	public String odds(String str,Double odds) {
		DecimalFormat df = new DecimalFormat("#0.000");
		Double oddss = Double.parseDouble(str);
		Double o =  oddss*odds;//算出平台和代理 之间的差
		return  df.format(oddss-o);//减掉之间的差距带到最终的结果
	}
	/**
	 * 方法名：syLotterr
	 * 描述：     查询所有正常开奖的彩种
	 * 参数：    @return
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/syLotterr1")
	public JsonResult syLotterr1() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		List<Data> lotterList = lotterService.getAllLotters1();
		for(Data data :lotterList) {
			data.setNextStopOrderTimeEpoch(data.getNextStopOrderTimeEpoch().replaceAll("-", "/"));
		}
		return new JsonResult(sdf.format(new Date()),lotterList);
	}

	/** 公告 */
	@ResponseBody
	@RequestMapping("/indexNotice")
	public JsonResult indexNotice(String type) {
		return new JsonResult("indexNotice", infoNotiService.getOneByNoticeDesc(type));
	}

	/** 轮播 */
	@ResponseBody
	@RequestMapping("/indexPicture")
	public JsonResult indexPicture() {
		return new JsonResult("indexPicture", infoNotiService.getOneByPictureDesc());
	}


	/** 查询购彩页面所有彩种信息- */
	@RequestMapping("/gc")
	public ModelAndView gc() {
		/** 获取所有lotter */
		List<LotterExample> lotterList = lotterService.getAllLotters();
		for (LotterExample lotterExample : lotterList) {
			lotterExample.setLotternumber(lotterExample.getLotternumber().replace(",", " "));
		}
		return new ModelAndView("include/gc").addObject("lotterList", lotterList);
	}

	/** 加载开奖页面- */
	@RequestMapping("/kj")
	public ModelAndView kj() {
		return new ModelAndView("include/kj");
	}

	/** 查询个人订单全部信息- */
	@RequestMapping("/dd")
	public ModelAndView dd(HttpSession session, String cname) {
		ModelAndView modelAndView = new ModelAndView("include/dd");
		modelAndView.addObject("myOrders",
				orderService.getMyOrders("all", cname, ((User) session.getAttribute("user")).getId()));
		return modelAndView;
	}

	/** 加载我的个人页面全部信息 */
	@RequestMapping("/wd")
	public ModelAndView wd(HttpSession session) {
		User user = (User) session.getAttribute("user");
		session.setAttribute("user", userService.login(user.getName(), user.getPass()));
		return new ModelAndView("include/wd").addObject("weidu", liushuiService.weidu(user.getId())).addObject("url","");
	}

	/** 加载购彩助手页面信息 */
	@RequestMapping("/help")
	public ModelAndView help(String url, String str) {
		ModelAndView modelAndView = new ModelAndView("/help");
		modelAndView.addObject("url", url.trim());
		modelAndView.addObject("str", str);
		return modelAndView;
	}

	/**
	 *   方法名：exit
	 *   描述：    加载退出登录页面信息
	 *   参数：    @param session
	 * @return: void
	 */
	@ResponseBody
	@RequestMapping(value = "/exit2", produces = {"application/json;charset=UTF-8"})
	public String exit2(HttpServletRequest request,HttpServletResponse response) {
		String token = request.getHeader("Token");
		System.out.println(token);
		Map<String,Object> map =new HashMap<>();

		try {
			String idStr = new String(DataEncryptUtil.decryptBASE64(token));
			int id = Integer.parseInt(idStr);
			User user = userService.getUserByid(id);
			if(user==null){
				map.put("msg","您还没有登录，请返回登录页面进行登录！");
				return JSON.toJSONString(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		map.put("msg","success");

		return JSON.toJSONString(map);

		//session.removeAttribute("user");
		/*Set<User> set = SessionListenerUtil.onlineNum(request);
		WebSocketJson w1 = new WebSocketJson(2,set.size());
		w1.sendAllHt();*/
		/*try {
			response.sendRedirect(request.getContextPath() + "/login.jsp");
		} catch (Exception e) {
		}*/
	}

	/**
	 * 合买订单
	 *
	 */

	/** 查询合买订单全部信息 */
	@RequestMapping("/hm")
	public ModelAndView hm(HttpSession session) {
		ModelAndView modelAndView = new ModelAndView("include/hm");
		List<JointVo> list = new ArrayList<JointVo>();
		/** 查询所有的订单号 */
		List<String> num = jointService.getFindJoint();
		/** 查询所有的合买发起信息 */
		for (int i = 0; i < num.size(); i++) {
			JointVo vo = jointService.getAllJoint(num.get(i));
			list.add(vo);
		}
		modelAndView.addObject("syfaqhm", list);
		modelAndView.addObject("lotters", lotteryService.getAllLotter());
		return modelAndView;
	}

	/** 查询有效订单的最新份数 */
	@ResponseBody
	@RequestMapping("/zuixinfs")
	public JsonResult zuixinfs(String orderNum) {
		/** 当前合买剩余份数 */
		Integer int1 = jointService.getScountJoint(orderNum);
		return new JsonResult(null, int1);
	}

	/** 查询个人发起合买订单 */
	@ResponseBody
	@RequestMapping("/ohm")
	public JsonResult ohm(HttpSession session) {
		User user = (User) session.getAttribute("user");
		/** 查询所有的订单号 */
		List<String> num = jointService.getOrderNum(0);
		/** 当前用户所有参与以及发起合买的信息 */
		List<JointVo> list = new ArrayList<JointVo>();
		for (int i = 0; i < num.size(); i++) {
			List<JointVo> vo = jointService.getOneJoint(num.get(i), user.getId());
			list.addAll(vo);
		}
		return new JsonResult("list", list);
	}

	/** 查询个人参与合买订单 */
	@ResponseBody
	@RequestMapping("/ohm1")
	public JsonResult ohm1(HttpSession session) {
		User user = (User) session.getAttribute("user");
		/** 查询所有的订单号 */
		List<String> num = jointService.getOrderNum(1);
		/** 当前用户所有参与以及发起合买的信息 */
		List<JointVo> list = new ArrayList<JointVo>();
		for (int i = 0; i < num.size(); i++) {
			List<JointVo> vo = jointService.getOneJoint1(num.get(i), user.getId());
			list.addAll(vo);
		}
		return new JsonResult("list1", list);
	}

	/** 查询历史合买信息 */
	@ResponseBody
	@RequestMapping("/lishiJl")
	public JsonResult lishiXinxi() {
		List<Joint> list3 = jointService.getLishiJl();
		return new JsonResult("lishiJl", list3);
	}

	/** 查询历史合买信息 */
	@ResponseBody
	@RequestMapping("/checkhm")
	public JsonResult checkhm(String orderNum, HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<Joint> joint4 = new ArrayList<Joint>();
		Joint joint1 = jointService.checkhm(orderNum, user.getId());
		try {
			joint1.getId();
			joint4.add(joint1);
			return new JsonResult("checkhm", joint4);
		} catch (Exception e) {
			/**
			 * 发起人胜率
			 */
			// 查询所有的发起人
			List<Joint> joint3 = jointService.chaxunfqr();
			List<Joint> joint2 = new ArrayList<Joint>();
			List<Integer> int1 = new ArrayList<Integer>();
			List<Integer> int2 = new ArrayList<Integer>();

			for (int i = 0; i < joint3.size(); i++) {
				// 查询发起人的所有发起次数
				int count1 = jointService.chaxunsycs(joint3.get(i).getUser());
				int1.add(count1);
				// 查询发起人的中奖次数
				int count2 = jointService.chaxunzjcs(joint3.get(i).getUser());
				int2.add(count1);
				// 计算胜率
				double slv1 = Double.parseDouble(count2 + "") / Double.parseDouble(count1 + "");
				int temp = (int) (slv1 * 10000);
				double result = (double) temp / 100;
				DecimalFormat dec = new DecimalFormat("#0.00");
				String result1 = dec.format(result);
				String slv2 = result1 + "%";
				Joint joint = new Joint();
				joint.setUser(joint3.get(i).getUser());
				joint.setShenglv(slv2);
				joint2.add(joint);
			}
			return new JsonResult("checkhm", joint2);
		}
	}

	/**
	 *
	 * 跟单订单
	 *
	 */

	/** 跟单页面 */
	@RequestMapping("/gendanPage")
	public String gendanPage() {
		return "/include/gendan";
	}

	/** 历史跟单 */
	@RequestMapping("/lishiGendan")
	public String lishiGendan() {
		return "/include/historyGenDan";
	}

	/** 跟单排行 */
	@RequestMapping("/gendanPai")
	public String gendanPai() {
		return "/include/gendanRank";
	}

	/** 查询当前可以购买的跟单 */
	@ResponseBody
	@RequestMapping("/gendan")
	public JsonResult gendan() {
		List<JointVo> vo = gendanService.getAllGendan();
		return new JsonResult("gendan", vo);
	}

	/** 查看已经失效的订单 */
	@ResponseBody
	@RequestMapping("/gdInvalid")
	public JsonResult gdInvalid() {
		List<JointVo> vo = gendanService.gdInvalid();
		return new JsonResult("gdInvalid", vo);
	}

	/** 跟单排行 */
	@ResponseBody
	@RequestMapping("/gdrankings")
	public JsonResult gdrankings(Integer key) {
		SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<JointVo> gens = new ArrayList<JointVo>();
		String time = "";
		if (key == 1) {
			time = ss.format(new Date()).substring(0, 10);
		} else if (key == 2) {
			time = ss.format(new Date()).substring(0, 10);
		} else if (key == 3) {
			time = ss.format(new Date()).substring(0, 7);
		} else if (key == 0) {
			time = "";
		}
		if (key == 2) {
			gens = gendanService.getIncomdeWeek(time);
		} else {
			gens = gendanService.getIncomdeGendan(time);
		}
		return new JsonResult("gdrankings", gens);
	}

	/** 查看某一条跟单的信息 */
	@ResponseBody
	@RequestMapping("/oneData")
	public JsonResult oneData(Integer id) {
		List<JointVo> list = gendanService.getOneData(id);
		/** 跟单人数 */
		return new JsonResult("oneData", list);
	}

	/** 跟单-倍数 */
	@ResponseBody
	@RequestMapping("/payCount")
	public JsonResult payCount() {
		Admin list = systemConfigService.findAllConfig();
		String beishu = list.getGendanbs();
		return new JsonResult("payCount", beishu);
	}

	/** 合买-跟单-开关 */
	@ResponseBody
	@RequestMapping("/cplayFlag")
	public JsonResult cplayFlag() {
		Admin list = systemConfigService.findAllConfig();
		Admin admin = new Admin();
		admin.setHemai(list.getHemai());
		return new JsonResult("flag", admin);
	}

	/** 跟单-购买进度 */
	@ResponseBody
	@RequestMapping("/shop")
	public JsonResult shop(HttpSession session) {
		User user = (User) session.getAttribute("user");
		Gendanlv gendanlv = gendanlvService.getFindRebate();
		int a1 = gendanlv.getSeveralTime();
		int cs1 = gendanService.getShopGendan(user.getId());
		return new JsonResult(cs1 + "", a1);
	}

	/** 查询自己发起的跟单 */
	@ResponseBody
	@RequestMapping("/fqgendan")
	public JsonResult fqgendan(HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<JointVo> list = gendanService.getFQGendan(user.getId());
		return new JsonResult("fqgendan", list);
	}

	/** 查询自己参与的跟单 */
	@ResponseBody
	@RequestMapping("/cygendan")
	public JsonResult cygendan(HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<JointVo> list = gendanService.getCYGendan(user.getId());
		return new JsonResult("cygendan", list);
	}

	/**
	 * 个人反水
	 */

	/**
	 *
	   *   方法名：fanshui
	   *   描述：     查询个人充值打码情况
	   *   参数：    @param session
	   *   参数：    @return
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/fanshui")
	public JsonResult fanshui(HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<String> list = fanshuiJlService.findUserWaterCount(user);
		return new JsonResult("fanshui", list);
	}

	/**
	 *
	   *   方法名：lotteryRecord
	   *   描述：      彩种信息
	   *   参数：    @return
	 * @return: ModelAndView
	 */
	@RequestMapping("/lotteryRecord")
	public ModelAndView lotteryRecord() {
		return new ModelAndView("u/lotteryRecord").addObject("lotters", lotteryService.getAllLotter());
	}

	/**
	 * 开奖记录
	 *
	 */

	/** 所有的开奖记录 */
	@ResponseBody
	@RequestMapping("/syjl")
	public JsonResult kaijiangjl() {
		List<Data> data = dataService.getSouyou();
		return new JsonResult("", data);
	}

	/** 某个彩种的开奖记录 */
	@ResponseBody
	@RequestMapping("/caizhongjl")
	public String czkjjl(String cname) {
		Map<String, Object> map = new HashMap<>();
		List<Data> data = dataService.getLimitDataInfo(cname);
		//return new JsonResult("caizhongjl", data);
		map.put("caizhongjl", data);
		return JSON.toJSONString(map);
	}

	/** 走势图 */
	@RequestMapping("/zoushitu")
	public String zoushitu() {
		return "include/zoushitu";
	}

	/** 走势图 */
	@RequestMapping("/trendchart")
	public ModelAndView trendchart() {
		ModelAndView m = new ModelAndView("include/trendchart");
		List<LotterExample> lotterList = lotterService.getAllLotters();
		m.addObject("list", lotterList);
		return m;
	}

	/** 充值提款记录 */
	@ResponseBody
	@RequestMapping("/laba")
	public JsonResult laba() {
		List<Jine> data = jineService.getAllJlLimit();
		return new JsonResult("cz", data);
	}

	/** 优惠活动页面 */
	@RequestMapping("/youhuihd")
	public String youhuihuodong() {
		return "/include/youhuihuodong";
	}

	/** 优惠活动页面 */
	@RequestMapping("/youhuiDetailjsp")
	public String youhuihuodongDetail() {
		return "/include/youhuihuodongDetail";
	}

	/** 优惠活动1 */
	@RequestMapping("/zhouzhoujiangli")
	public String zhouzhoujl() {
		return "/noticeWebSite/zhouzhoujiangli";
	}

	/**
	 *   方法名：kfurl
	 *   描述：    在线QQ客服地址
	 *   参数：    @return
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/kfurl")
	public JsonResult kfurl() {
		List<QqKeFu> data = qqKeFuService.getAllQqKeFu();
		return new JsonResult("success", data);
	}

	/**
	 *   方法名：kaijiangjilu
	 *   描述：    开奖大厅彩种开奖记录
	 *   参数：    @param cname 彩种名称
	 *   参数：    @return
	 * @return: JsonResult
	 */
	@RequestMapping("/kaijiangjilu")
	@ResponseBody
	public JsonResult kaijiangjilu(String cname) {
		return new JsonResult("success",dataService.getLimitDataInfo(cname));
	}


	/**
	 *   方法名：damals
	 *   描述：     用户打码所需
	 *   参数：    @param session
	 *   参数：    @return
	 * @return: ModelAndView
	 */
	@RequestMapping("/damals")
	public ModelAndView damals(HttpSession session) {
		ModelAndView m = new ModelAndView("/include/damals");
		User user = (User) session.getAttribute("user");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time = sdf.format(new Date());
		m.addObject("damal", orderService.getCnameDama(user.getId(), time));
		return m;
	}

	/**
	 *   方法名：damalType
	 *   描述：   用户每日-每月-历史 打码统计
	 *   参数：    @param type 查询时间类型
	 *   参数：    @param session
	 *   参数：    @return
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/damalType")
	public JsonResult damalType(Integer type, HttpSession session) {
		User user = (User) session.getAttribute("user");
		return damaService.findByTimeCodeCount(type,user.getId());
	}

	/**
	 *   方法名：download
	 *   描述：    手机下载页面
	 *   参数：    @param model model对象
	 *   参数：    @param request
	 *   参数：    @param session
	 *   参数：    @return
	 * @return: ModelAndView
	 */
	@RequestMapping("/download")
	public ModelAndView download(ModelAndView model, HttpServletRequest request, HttpSession session) {
		if (request.getQueryString() != null) {
			String refCode = request.getServerName() + "?" + (request.getQueryString());
			session.setAttribute("refCode", refCode);
		}
		AppDownload app = adminService.findAppImgPath();
		model.setViewName("include/download");
		model.addObject("webSite", WebsiteStateConfig.configs.get("wangzhantitle"));
		model.addObject("app", app);
		model.addObject("url", request.getHeader("Referer"));
		return model;
	}


	 /**
	  *   方法名：findNextPeriod
	  *   描述：    查询彩种下期开奖时间
	  *   参数：    @param cname 彩种名称
	  *   参数：    @param period 彩种期号
	  *   参数：    @return
	  * @return: JsonResult
	  */
	 @ResponseBody
	 @RequestMapping(value = "/findNextNextPeriod", produces = {"application/json;charset=UTF-8"})
	 public String findNextNextPeriod(String cname,Integer type) {
		 Map<String, Object> map = new HashMap<>();
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		 Data data = dataService.findNextNextPeriod(cname,type);

		 Lotter timespace = lotterService.getByCname(cname);
		 map.put("timespace",timespace.getTimespace());

		 /**
		  * 以下为修改后代码
		  */
//		 Data data =new Data();
//		 data.setCname("xjssc");
//		 data.setGameNameInChinese("新疆时时彩");
//		 data.setLottertime("2019-06-03 18:17:00");
//		 data.setNextStopOrderTimeEpoch("2019-06-03 18:37:00");
//		 data.setPeriod("20190603024");
//		 data.setNextperiod("20190603025");
//		 data.setLotternumber("0,5,0,2,9,");
//		 data.setPlayResult("小单|虎");
//		 data.setPaijtime("2019-06-03 18:14:00");
//		 data.setTouzhuzt("已结束");
//		 data.setState("已开奖");
//		 data.setType(0);
//		 data.setStatus(1);
//		 data.setOpenTime("2019-06-03 16:57:00");



		 if(data != null) {
			 data.setNextStopOrderTimeEpoch(data.getNextStopOrderTimeEpoch().replaceAll("-", "/"));
		 }
		 map.put("systemTime",sdf.format(new Date()));
		/* map.put(sdf.format(new Date()),data);*/
		 map.put("lotterData",data);
		 return JSON.toJSONString(map);
	 }


	 /**
	  *   方法名：whNotice
	  *   描述：   查询维护公告
	  *   参数：    @return
	  * @return: JsonResult
	  */
	 @ResponseBody
	 @RequestMapping("/whNotice")
	 public JsonResult whNotice() {
		 return new JsonResult("",infoNotiService.whNotice());
	 }



	/**
	 *   方法名：chatroomFlag
	 *   描述：    查询聊天室是否开启
	 *   参数：    @return
	 * @return: JsonResult
	 */
	 @ResponseBody
	 @RequestMapping("/chatroom")
    public JsonResult chatroomFlag() {
    	return new JsonResult("chatroom",Integer.parseInt(WebsiteStateConfig.configs.get("chatroomFlag")));
    }
	 /**
	  *首页获取数据的请求
	  * 查询彩种当前状态  就只是单独的查询了 彩种名cname 和 他的state状态 不管开启还是关闭都会被查询出来
	  * @return 查询到则返回list集合包含colorVariety实体数据 没有查询到则返回空集合
	  */
	 @ResponseBody
	 @RequestMapping("/colorVariety")
	 public JsonResult colorVariety(HttpSession session) {
		 //彩种关闭开启方法
		 List<ColorVariety> list = new ArrayList<ColorVariety>();
		 for(Lotter l : WebsiteStateConfig.lotteryState) {
			 if(!"jlk3".equals(l.getCname().trim()) && !"klpk".equals(l.getCname().trim())  && !"zc".equals(l.getCname().trim())  && !"jnd28".equals(l.getCname().trim())) {
				 list.add(new ColorVariety(l.getCname(),l.getState()));
			 }
		}
		 return new JsonResult(null,list);
	 }

	 /**
		 * 方法名：createUserName
		 * 描述：    随机生成用户名
		 * 参数：    @param length
		 * 参数：    @return
		 * @return: String
		 */
		public String createUserName(int length) {
			// 定义一个字符串（A-Z，a-z，0-9）即62位；
			String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
			// 由Random生成随机数
			Random random = new Random();
			StringBuffer sb = new StringBuffer();
			// 长度为几就循环几次
			for (int i = 0; i < length; ++i) {
				// 产生0-61的数字
				int number = random.nextInt(62);
				// 将产生的数字通过length次承载到sb中
				sb.append(str.charAt(number));
			}
			// 将承载的字符转换成字符串
			return sb.toString();
		}

		/***
		 * 方法名：createLotteryName
		 * 描述：    随机取彩种名称
		 * 参数：    @param num
		 * 参数：    @return
		 * @return: int
		 */
		public int createLotteryName(int num) {
			while (true) {
				int ii = (int) (1 + Math.random() * num);
				if (num >= ii) {
					return ii;
				}
			}
		}


		/**
		  * 方法名：findUserNotices
		  * 描述：    查询用户通知信息
		  * 参数：    @return
		 * @return: JsonResult
		 */
		@RequestMapping("/findUserNotices")
		@ResponseBody
		public JsonResult findUserNotices() {
			return new JsonResult("success",infoNotiService.findAllUserNotices());
		}

		/**
		 *
		 * ----TODO：更换地址的请求
		 *
		 */

		/** 试玩开启 */
		@ResponseBody
		@RequestMapping("/cplays")
		public JsonResult cplays() {
			Integer a = adminService.getCplay();
			return new JsonResult("cplays", a);
		}


}
